<?php

  require_once 'DB.php';
  include_once("./libraries/db.inc.php");
  include_once("./libraries/util.inc.php");
  include_once("./libraries/authentication.inc.php");

  function checkLogin($loginUsername, $loginPassword, $connection) {
    //see if the username and password match a valid user
    if (authenticateUser($loginUsername, $loginPassword, $connection)) {
      //if so, then register this session
      //registerLogin($loginUsername); //session registered automatically
      
      //clear these vars so a future <form> is blank??
      unset($_SESSION["loginFormVars"]);
      unset($_SESSION["loginErrors"]);
      unset($_SESSION["message"]);

      //and redirect back to the main page
      header("Location: index.php");
      $connection->disconnect();
      exit;

    } else {
      //otherwise we should not allow the login
      //so display an error
      $_SESSION["message"] = "Username or password incorrect. " .
                             "Login failed.";

      //and go back to the login page
      header("Location: login.php");
      $connection->disconnect();
      exit;

    }
  }


  session_start();

  $connection = DB::connect($dsn, $options);
  if (DB::isError($connection)) {
    echo "error1...";
    echo $connection->getMessage();
    echo $connection->getCode();
    echo $connection->getUserInfo();
    echo $connection->getDebugInfo();
    trigger_error($connection->getMessage(), E_USER_ERROR);
  }

  //check if the user is already logged in
  if (isset($_SESSION["loginUsername"])) {
    $_SESSION["message"] = "You are already logged in as {$_SESSION["loginUsername"]}";
    header("Location: index.php");
    $connection->disconnect();
    exit;
  }

  //register and clear an error array
  if (isset($_SESSION["loginErrors"])) {
    unset($_SESSION["loginErrors"]);
  }
  $_SESSION["loginErrors"] = array();

  //set up formVars array for the POST variables
  $_SESSION["loginFormVars"] = array();
  $_SESSION["loginFormVars"]["loginUsername"] = $_POST["loginUsername"];
  $_SESSION["loginFormVars"]["loginPassword"] = $_POST["loginPassword"];

  checkLogin($_SESSION["loginFormVars"]["loginUsername"],
             $_SESSION["loginFormVars"]["loginPassword"],
             $connection);

?>
